const express = require('express')
const router = express.Router()
const path = require('path');
const fs = require('fs');
const multer = require('multer');
const ImgUrl=require('../models/imgurl')
// 确保上传目录存在
const uploadDir = path.join(__dirname, 'uploads');
if (!fs.existsSync(uploadDir)) {
    fs.mkdirSync(uploadDir);
}
// 设置文件上传
const storage = multer.diskStorage({
    destination: (req, file, cb) => {
        cb(null, 'uploads/'); // 定义存储路径
    },
    filename: (req, file, cb) => {
        cb(null, `${Date.now()}-${file.originalname}`); // 定义文件名
    }
});
  // 创建 Multer 实例，传入存储配置
const upload = multer({ storage: storage });
// 上传图片
router.post('/fileUpload',upload.single('url'),(req,res)=>{
    if (!req.file) {
        return res.status(400).json({ error: 'No file uploaded' });
    }
    const url = `http://localhost:8080/uploads/${req.file.filename}`;// 获取文件路径,拼接路径
    console.log(url);
    ImgUrl.create({
        url: url // 将路径保存到数据库
    }).then(doc => {
        res.json({ data: doc.url });
    }).catch(err => {
        res.status(500).json({ error: 'Database error', details: err });
    });
})
module.exports = router